package com.example.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.common.ResultCode;
import com.example.dao.TeacherInfoDao;
import com.example.entity.Account;
import com.example.entity.Admininfo;
import com.example.entity.TeacherInfo;
import com.example.exception.CustomException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 涛某
 * @version 1.0
 * @date 2024/3/21 13:53
 */
@Service
public class TeacherInfoService {

    @Autowired
    private TeacherInfoDao teacherInfoDao;

    public void update(TeacherInfo teacherInfo) {
        teacherInfoDao.update(teacherInfo);
    }

    public void add(TeacherInfo teacherInfo) {
        TeacherInfo info = teacherInfoDao.FindByName(teacherInfo.getName());
        //先查看用户名是否已经存在
        if (ObjectUtil.isNotEmpty(info)){
            throw new CustomException(ResultCode.USER_EXIST_ERROR);
        }
        //如果不存在的话就赋予一个初始密码
        if (ObjectUtil.isEmpty(teacherInfo.getPassword())){
            teacherInfo.setPassword("123456");
        }
        teacherInfoDao.add(teacherInfo);

    }

    public List<TeacherInfo> findAll() {
        return teacherInfoDao.findAll();
    }

    public void deleteById(Long id) {
        teacherInfoDao.deleteById(id);
    }

    public PageInfo<TeacherInfo> findPage(Integer pageNum, Integer pageSize) {

        //开始分页
        PageHelper.startPage(pageNum,pageSize);
        //查询会根据pageNum pageSize 来查询相应数据
        List<TeacherInfo> infos = teacherInfoDao.selectAll();
        return PageInfo.of(infos);
    }

    public PageInfo<TeacherInfo> findPageName(Integer pageNum, Integer pageSize, String name) {
        //开始分页
        PageHelper.startPage(pageNum,pageSize);
        List<TeacherInfo> infos = teacherInfoDao.findByNamePage(name);
        return PageInfo.of(infos);
    }

    public Account login(String name, String password) {
        TeacherInfo teacherInfo = teacherInfoDao.findByNameAndPassowrd(name, password);
        if (ObjectUtil.isEmpty(teacherInfo)){
            throw new CustomException("1","用户名或者密码输入错误");
        }
        return teacherInfo;

    }

    public TeacherInfo FindById(Long id) {
        return  teacherInfoDao.FindById(id);
    }

    public void register(TeacherInfo teacherInfo) {
        //在service里层里对输入进来的用户进行校验
        //先对用户名的名字进行一个检查查看用户名是否被占用


            TeacherInfo info = teacherInfoDao.FindByName(teacherInfo.getName());
            if (ObjectUtil.isNotEmpty(info)){
                throw new CustomException(ResultCode.USER_EXIST_ERROR);
            }else {
                teacherInfoDao.add(teacherInfo);
            }


        //校验通过了在调用方法把数据添加到数据库中

    }
}
